<template>
    <view class="u-count-num-container">
        <view
            class="u-count-num-box"
            v-for="(char, index) in displayValue"
            :key="index"
        >
            <text
                class="u-count-num"
                :style="{
                    color: color
                }"
            >{{ char }}</text>
        </view>
    </view>
</template>

<script>
import props from './props.js';

export default {
    name: 'u-count-to',
    data() {
        return {
            localStartVal: this.startVal,
            displayValue: this.formatNumber(this.startVal),
            printVal: null,
            paused: false, // 是否暂停
            localDuration: Number(this.duration),
            startTime: null, // 开始的时间
            timestamp: null, // 时间戳
            remaining: null, // 停留的时间
            rAF: null,
            lastTime: 0 // 上一次的时间
        };
    },
    mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
    computed: {
        countDown() {
            return this.startVal > this.endVal;
        }
    },
    watch: {
        startVal() {
            this.autoplay && this.start();
        },
        endVal() {
            this.autoplay && this.start();
        }
    },
    mounted() {
        this.autoplay && this.start();
    },
    methods: {
        easingFn(t, b, c, d) {
            return (c * (-Math.pow(2, (-10 * t) / d) + 1) * 1024) / 1023 + b;
        },
        requestAnimationFrame(callback) {
            const currTime = new Date().getTime();
            // 为了使setTimteout的尽可能的接近每秒60帧的效果
            const timeToCall = Math.max(0, 16 - (currTime - this.lastTime));
            const id = setTimeout(() => {
                callback(currTime + timeToCall);
            }, timeToCall);
            this.lastTime = currTime + timeToCall;
            return id;
        },
        cancelAnimationFrame(id) {
            clearTimeout(id);
        },
        // 开始滚动数字
        start() {
            this.localStartVal = this.startVal;
            this.startTime = null;
            this.localDuration = this.duration;
            this.paused = false;
            this.rAF = this.requestAnimationFrame(this.count);
        },
        // 暂定状态，重新再开始滚动；或者滚动状态下，暂停
        reStart() {
            if (this.paused) {
                this.resume();
                this.paused = false;
            } else {
                this.stop();
                this.paused = true;
            }
        },
        // 暂停
        stop() {
            this.cancelAnimationFrame(this.rAF);
        },
        // 重新开始(暂停的情况下)
        resume() {
            if (!this.remaining) return
            this.startTime = 0;
            this.localDuration = this.remaining;
            this.localStartVal = this.printVal;
            this.requestAnimationFrame(this.count);
        },
        // 重置
        reset() {
            this.startTime = null;
            this.cancelAnimationFrame(this.rAF);
            this.displayValue = this.formatNumber(this.startVal);
        },
        count(timestamp) {
            if (!this.startTime) this.startTime = timestamp;
            this.timestamp = timestamp;
            const progress = timestamp - this.startTime;
            this.remaining = this.localDuration - progress;
            if (this.useEasing) {
                if (this.countDown) {
                    this.printVal = this.localStartVal - this.easingFn(progress, 0, this.localStartVal - this.endVal, this.localDuration);
                } else {
                    this.printVal = this.easingFn(progress, this.localStartVal, this.endVal - this.localStartVal, this.localDuration);
                }
            } else {
                if (this.countDown) {
                    this.printVal = this.localStartVal - (this.localStartVal - this.endVal) * (progress / this.localDuration);
                } else {
                    this.printVal = this.localStartVal + (this.endVal - this.localStartVal) * (progress / this.localDuration);
                }
            }
            if (this.countDown) {
                this.printVal = this.printVal < this.endVal ? this.endVal : this.printVal;
            } else {
                this.printVal = this.printVal > this.endVal ? this.endVal : this.printVal;
            }
            this.displayValue = this.formatNumber(this.printVal) || 0;
            if (progress < this.localDuration) {
                this.rAF = this.requestAnimationFrame(this.count);
            } else {
                this.$emit('end');
            }
        },
        // 判断是否数字
        isNumber(val) {
            return !isNaN(parseFloat(val));
        },
        formatNumber(num) {
            // 将num转为Number类型，因为其值可能为字符串数值，调用toFixed会报错
            num = Number(num);
            
            // 确保小数点后有两位数
            let formattedNum = num.toFixed(Number(this.decimals) || 2);
            
            // 分割成整数部分和小数部分
            formattedNum += '';
            const parts = formattedNum.split('.');
            
            // 获取整数部分
            let integerPart = parts[0];
            
            // 添加前导零
            while (integerPart.length < 8) { // 8是因为包括了前面的00000
                integerPart = '0' + integerPart;
            }
            
            // 获取小数部分
            const decimalPart = parts.length > 1 ? this.decimal + parts[1] : '';
            
            // 如果设置了千位分隔符，则应用之
            if (this.separator && !this.isNumber(this.separator)) {
                const rgx = /(\d+)(\d{3})/;
                while (rgx.test(integerPart)) {
                    integerPart = integerPart.replace(rgx, '$1' + this.separator + '$2');
                }
            }
            
            return integerPart + decimalPart;
        },
        destroyed() {
            this.cancelAnimationFrame(this.rAF);
        }
    }
};
</script>

<style lang="scss" scoped>
@import "../../libs/css/components.scss";

.u-count-num-container {
    display: flex;
    align-items: center;
	flex-direction:row;
}

.u-count-num-box {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 30px; // 根据需要调整宽度
    height: 80rpx; // 根据需要调整高度
    background-color: #fefbec; // 淡黄色背景
    border: 1rpx solid rgb(222,223,167); // 黑色边框
    margin-right: 6rpx; // 字与字之间的间距
    box-sizing: border-box;
	border-radius: 7rpx;
}

.u-count-num {
    text-align: center;
    color: #303030 !important; // 黑色字体
	font-size: 50rpx;
	font-weight: bold;
}
</style>